package com.zx.rabbitmq.java.work.polling;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author Zx
 * @date 2021/4/18 14:35
 */
public class Producer {
    public static void main(String[] args) {
        // 所有的中间件技术都是基于tcp/IP协议的基础之上构建的, rabbitmq是用amqp
        // ip:port

        // 1 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.15.3.32");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("admin");


        Connection connection = null;
        Channel channel = null;
        try {
            // 2 创建连接connection
            connection = connectionFactory.newConnection("生产者");
            // 3 通过连接获取通道channel
            channel = connection.createChannel();
            // 4 通过channel 创建交换机, 声明队列, 绑定关系, 路由key, 发送消息, 和接收消息
            String queueName = "queue4";

            // 准备交换机
            String exchangeName = "direct_message_exchange";
            // 定义路由key
            String routingKey = "email";
            // 指定交换机类型 direct/topic/fanout/headers
            String exchangeType = "direct";
            // 声明交换机
            channel.exchangeDeclare(exchangeName, exchangeType, true);
            /*
             * @param1 队列名称
             * @param2 是否持久化
             * @param3 排他性, 是否是独占独立
             * @param4 是否自动删除, 随着最后一个费者消费完毕消息以后是否把队列自动删除
             * @param5 附属参数attachData
             */
            channel.queueDeclare(queueName, true, false, false, null);
            // 绑定队列到交换机
            channel.queueBind(queueName, exchangeName, routingKey);


            for (int i = 0; i < 20; i++) {
                // 准备消息内容
                String message = "hello" + i;
                // 5 发送消息给队列queue
                channel.basicPublish(exchangeName, routingKey, null, message.getBytes());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6 关闭连接
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 7 关闭channel
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
